#include "imagewidget.h"
#include "PopupMenu.h"
#include "WPData.h"

#include <QKeyEvent>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QFileInfo>
#include <QPushButton>

ImageWidget::ImageWidget(const WPDataBlog& aBlog, const QPixmap& aPixmap, const QString& aFilename, QWidget *parent)
    : QWidget(parent)
    , iBlog(aBlog)
    , iPixmap(aPixmap.scaled(QSize(80,80)))
    , iFilename(aFilename)
    , iMouseDown(false)
    , iPopupMenu(0)
    , iRotationAngle(0)
    , iTargetSize(0,0)
    , iAlignment(WPMediaFile::Bottom)
    , iAlignText(tr("Bottom"))
{
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);

    iImage = new QLabel();
    iImage->setMargin(10);
    iImage->setPixmap(aPixmap);
    iImage->setFixedSize(80,80);

    iAlignButton = new QPushButton();
    iAlignButton->setText(tr("Align"));
    connect(iAlignButton,SIGNAL(clicked()),this,SLOT(ShowAlignMenu()));

    iResolutionButton = new QPushButton();
    iResolutionButton->setText(tr("Resolution"));
    connect(iResolutionButton,SIGNAL(clicked()),this,SLOT(ShowResolutionMenu()));
    if (!iBlog.iEndpoint.iResizePhotos) {
        iResolutionButton->setEnabled(false);
    }

//    iTextLabel = new QLabel(this);
//    iTextLabel->setMargin(10);
//    iTextLabel->setFixedWidth(parentWidget()->contentsRect().width() - 100);

    layout->addWidget(iImage);
    layout->addWidget(iAlignButton);
    layout->addWidget(iResolutionButton);
//    layout->addWidget(iTextLabel);

    setFixedHeight(80);
    setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    setLayout(layout);

    ResizeOriginal();
}

ImageWidget::~ImageWidget()
{
    delete iPopupMenu;
}

int ImageWidget::RotationAngle() const
{
    return iRotationAngle;
}

const QSize& ImageWidget::TargetSize() const
{
    return iTargetSize;
}

const QString& ImageWidget::FileName() const
{
    return iFilename;
}

WPMediaFile::Align ImageWidget::Alignment() const
{
    return iAlignment;
}

WPMediaFile::SizeType ImageWidget::SizeType() const
{
    return iSizeType;
}

void ImageWidget::mousePressEvent(QMouseEvent *e)
{
    iMouseDown = true;
    iMousePos = e->pos();
    if (!iPopupMenu) {
        setStyleSheet("background-color: #B2D9FB;");
    }
    QWidget::mouseMoveEvent(e);
    update();
}

void ImageWidget::mouseMoveEvent(QMouseEvent *e)
{
    if ((e->pos()-iMousePos).manhattanLength() > 10)
    {
        iMouseDown = false;
        setStyleSheet("");
        update();
    }
    QWidget::mouseMoveEvent(e);
}

void ImageWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if (iMouseDown)
    {
        ShowContextMenu();
        iMouseDown = false;
        e->accept();
        update();
    }
    else
    {
        QWidget::mouseReleaseEvent(e);
    }
}

void ImageWidget::keyPressEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_Select)
    {
        e->accept();
    }
    else
    {
        QWidget::keyPressEvent(e);
    }
}

void ImageWidget::resizeEvent(QResizeEvent* event)
{
    Q_UNUSED(event);
    //iTextLabel->setFixedWidth(parentWidget()->contentsRect().width() - 100);
    if (iPopupMenu && iPopupMenu->isVisible())
        iPopupMenu->move(getMenuLocation(geometry().topRight()));
}

void ImageWidget::ShowResolutionMenu()
{
    // Resizing / View size.
    iPopupMenu = new PopupMenu();
    iPopupMenu->setFocus();
    connect(iPopupMenu,SIGNAL(aboutToHide()),this,SLOT(MenuHidden()));

    QAction *originalSizeAction = new QAction(tr("Set original size"), this);
    QAction *thumbnailSizeAction = new QAction(tr("Set thumbnail size"), this);
    QAction *mediumSizeAction = new QAction(tr("Set medium size"), this);
    QAction *largeSizeAction = new QAction(tr("Set large size"), this);
    iPopupMenu->addAction(originalSizeAction);
    iPopupMenu->addAction(thumbnailSizeAction);
    iPopupMenu->addAction(mediumSizeAction);
    iPopupMenu->addAction(largeSizeAction);
    connect(originalSizeAction,SIGNAL(triggered()),this,SLOT(ResizeOriginal()));
    connect(thumbnailSizeAction,SIGNAL(triggered()),this,SLOT(ResizeThumbnail()));
    connect(mediumSizeAction,SIGNAL(triggered()),this,SLOT(ResizeMedium()));
    connect(largeSizeAction,SIGNAL(triggered()),this,SLOT(ResizeLarge()));

    iPopupMenu->popup(getMenuLocation(QPoint(parentWidget()->width(),0)));
}

void ImageWidget::ShowAlignMenu()
{
    iPopupMenu = new PopupMenu();
    iPopupMenu->setFocus();
    connect(iPopupMenu,SIGNAL(aboutToHide()),this,SLOT(MenuHidden()));

    // Alignment.
    QAction *alignLeftAction = new QAction(tr("Add to left"),this);
    QAction *alignRightAction = new QAction(tr("Add to right"),this);
    QAction *alignBottomAction = new QAction(tr("Add to bottom"),this);
    QAction *alignTopAction = new QAction(tr("Add to top"),this);
    iPopupMenu->addAction(alignLeftAction);
    iPopupMenu->addAction(alignRightAction);
    iPopupMenu->addAction(alignBottomAction);
    iPopupMenu->addAction(alignTopAction);
    connect(alignLeftAction,SIGNAL(triggered()),this,SLOT(AlignLeft()));
    connect(alignRightAction,SIGNAL(triggered()),this,SLOT(AlignRight()));
    connect(alignBottomAction,SIGNAL(triggered()),this,SLOT(AlignBottom()));
    connect(alignTopAction,SIGNAL(triggered()),this,SLOT(AlignTop()));

    iPopupMenu->popup(getMenuLocation(QPoint(parentWidget()->width()/3*2,0)));
}
void ImageWidget::ShowContextMenu()
{
    iPopupMenu = new PopupMenu();
    iPopupMenu->setFocus();
    connect(iPopupMenu,SIGNAL(aboutToHide()),this,SLOT(MenuHidden()));

    // Rotation
    QAction *rotateLeftAction = new QAction(tr("Rotate left"), this);
    QAction *rotateRightAction = new QAction(tr("Rotate right"), this);
    iPopupMenu->addAction(rotateLeftAction);
    iPopupMenu->addAction(rotateRightAction);
    connect(rotateLeftAction,SIGNAL(triggered()),this,SLOT(RotateLeft()));
    connect(rotateRightAction,SIGNAL(triggered()),this,SLOT(RotateRight()));

    QAction *removePhotoAction = new QAction(tr("Remove"), this);
    iPopupMenu->addAction(removePhotoAction);
    connect(removePhotoAction,SIGNAL(triggered()),this,SLOT(doRemoveClicked()));

    iPopupMenu->popup(getMenuLocation(QPoint(iPopupMenu->sizeHint().width(),0)));
}

QPoint ImageWidget::getMenuLocation(QPoint itemPoint)
{
    itemPoint.setY(itemPoint.y() - 5);
    //QPoint globalItemPoint = mapToGlobal(itemPoint);
    QSize size = iPopupMenu->sizeHint();
    // Set popup a couple of pixels away from the screen right edge
    itemPoint.setX(itemPoint.x() - size.width());
    return mapToGlobal(itemPoint);
}

void ImageWidget::RefreshText()
{
    //QFileInfo fileInfo(iFilename);
    QString text;

    if (iBlog.iEndpoint.iResizePhotos && !iTargetSize.isNull()) {
        text.append(QString::number(iTargetSize.width())
                    + " X "
                    + QString::number(iTargetSize.height()));
    } else {
        text.append(iSizeText);
    }

    iResolutionButton->setText(text);
    iAlignButton->setText(iAlignText);
    //iTextLabel->setText(fileInfo.fileName());
}

void ImageWidget::MenuHidden()
{
    setStyleSheet("");
    iPopupMenu->deleteLater();
    iPopupMenu = NULL;
    update();
}

void ImageWidget::AlignLeft()
{
    iAlignText = QString(tr("Left"));
    iAlignment = WPMediaFile::Left;
    RefreshText();
}

void ImageWidget::AlignRight()
{
    iAlignText = QString(tr("Right"));
    iAlignment = WPMediaFile::Right;
    RefreshText();
}

void ImageWidget::AlignBottom()
{
    iAlignText = QString(tr("Bottom"));
    iAlignment = WPMediaFile::Bottom;
    RefreshText();
}

void ImageWidget::AlignTop()
{
    iAlignText = QString(tr("Top"));
    iAlignment = WPMediaFile::Top;
    RefreshText();
}

void ImageWidget::ResizeOriginal()
{
    iSizeText = tr("Original");
    iSizeType = WPMediaFile::Full;
    iTargetSize = QSize(0,0);
    RefreshText();
}

void ImageWidget::ResizeThumbnail()
{
    if (iBlog.iEndpoint.iResizePhotos) {
        iSizeType = WPMediaFile::Full;
        iTargetSize = iBlog.iThumbnailSize;
    } else {
        iSizeText = tr("Thumbnail");
        iSizeType = WPMediaFile::Thumbnail;
        iTargetSize = QSize(0,0);
    }

    RefreshText();
}

void ImageWidget::ResizeMedium()
{
    if (iBlog.iEndpoint.iResizePhotos) {
        iSizeType = WPMediaFile::Full;
        iTargetSize = iBlog.iMediumSize;
    } else {
        iSizeText = tr("Medium");
        iSizeType = WPMediaFile::Medium;
        iTargetSize = QSize(0,0);
    }

    RefreshText();
}

void ImageWidget::ResizeLarge()
{
    if (iBlog.iEndpoint.iResizePhotos) {
        iSizeType = WPMediaFile::Full;
        iTargetSize = iBlog.iLargeSize;
    } else {
        iSizeText = tr("Large");
        iSizeType = WPMediaFile::Large;
        iTargetSize = QSize(0,0);
    }

    RefreshText();
}

void ImageWidget::RotateLeft()
{
    QMatrix mat;
    mat.rotate(-90);
    iImage->setPixmap(iImage->pixmap()->transformed(mat));
    iRotationAngle -= 90;
    if (iRotationAngle == -360)
        iRotationAngle = 0;
}

void ImageWidget::RotateRight()
{
    QMatrix mat;
    mat.rotate(90);
    iImage->setPixmap(iImage->pixmap()->transformed(mat));
    iRotationAngle += 90;
    if (iRotationAngle == 360)
        iRotationAngle = 0;
}

void ImageWidget::doRemoveClicked()
{
    emit removeClicked(this);
}


